<template>
  <div class="app-container">
      <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>运费列表</span>
      <el-button class="btn-add" @click="handleAddFreight()" size="medium" type="primary">
        新增运费
      </el-button>
    </el-card>
    <el-table ref="productTable"
      :data="list"
      style="width: 100%"
      v-loading="listLoading"
      border>
        <!-- <el-table-column type="selection" width="60" align="center"></el-table-column> -->
        <!-- <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{scope.row.id}}</template>
        </el-table-column>
        <el-table-column label="头像" width="120" align="center">
          <template slot-scope="scope"><img style="height: 80px" :src="scope.row.icon"></template>
        </el-table-column> -->
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{scope.row.id}}</template>
        </el-table-column>
        <el-table-column label="运费名称" width="200" align="center">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
        <el-table-column label="包邮基础价" width="150" align="center">
          <template slot-scope="scope">{{scope.row.freeAmount}}</template>
        </el-table-column>
        <el-table-column label="运费" width="150" align="center">
          <template slot-scope="scope">{{scope.row.postage}}</template>
        </el-table-column>
        <el-table-column label="仓库名称" width="200" align="center">
          <template slot-scope="scope">{{scope.row.depotName}}</template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
              <el-button
                size="mini"
                @click="handleEditFreight(scope.$index, scope.row)">编辑
              </el-button>
              <!-- <el-button
                size="mini"
                @click="handleUpdateDepot(scope.$index, scope.row)">绑定仓库
              </el-button> -->
              <el-button
                size="mini"
                type="danger"
                @click="handleDeleteFreight(scope.$index, scope.row)">删除
              </el-button>
          </template>
        </el-table-column>
    </el-table>
    <!-- 新增运费的弹窗 -->
    <el-dialog title="新增运费" :visible.sync="isNewFreightOpen" :close-on-click-modal="false" :show-close="true" class="adjustmentBox">
        <el-form ref="newForm" :model="newForm" style="width:28rem;" :rules="newFormRules" >
          <el-form-item label="运费名称" prop="name" required label-width="6rem">
            <el-input v-model="newForm.name" placeholder="" style="width:16.66rem;"></el-input>
          </el-form-item>
          <el-form-item label="包邮基础价" prop="freeAmount" required label-width="6rem">
            <el-input v-model="newForm.freeAmount" placeholder="" style="width:15rem;"></el-input>
          </el-form-item>
           <el-form-item label="运费" prop="postage" required label-width="6rem">
            <el-input v-model="newForm.postage" placeholder="" style="width:15rem;"></el-input>
          </el-form-item>
        
          <el-form-item label="选择仓库" required label-width="6rem">
            <el-select v-model="newForm.depotId" placeholder="请选择" @change="depotChange">
              <el-option
                v-for="item in depotList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="saveNewFreight('newForm')" style="color:#fff;background-color:#417FF6;">保存</el-button>
            <el-button @click="isNewFreightOpen = false">关闭</el-button>
        </div>
    </el-dialog>
    <!-- 编辑运费的弹窗 -->
    <el-dialog title="编辑运费" :visible.sync="isEditFreightOpen" :close-on-click-modal="false" :show-close="true" class="adjustmentBox">
        <el-form :model="editForm" style="width:28rem;" :rules="editFormRules" >
           <el-form-item label="运费名称" prop="name" required label-width="6rem">
            <el-input v-model="editForm.name" placeholder="" style="width:16.66rem;"></el-input>
          </el-form-item>
          <el-form-item label="包邮基础价" prop="freeAmount" required label-width="6rem">
            <el-input v-model="editForm.freeAmount" placeholder="" style="width:15rem;"></el-input>
          </el-form-item>
           <el-form-item label="运费" prop="postage" required label-width="6rem">
            <el-input v-model="editForm.postage" placeholder="" style="width:15rem;"></el-input>
          </el-form-item>
        
          <el-form-item label="选择仓库" required label-width="6rem">
            <el-select v-model="editForm.depotId" placeholder="请选择" @change="depotChange">
              <el-option
                v-for="item in depotList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="saveFreightInfo('editForm')" style="color:#fff;background-color:#417FF6;">保存</el-button>
            <el-button @click="isEditFreightOpen = false">关闭</el-button>
        </div>
    </el-dialog>
    
  </div>
</template>
<script>
    import {
    fetchList,
    updateFreight,
    createFreight,
    deleteFreight,
    checkFreight,//查询运费模版明细
    // getCurFreightRole,
    // updateFreightRoleInfo,
  } from '@/api/freight'
   import {fetchList as fetchDepotList} from '@/api/depository'
 //  import {fetchRoleList} from '@/api/Freight'
//   import {fetchList as fetchProductAttrList} from '@/api/productAttr'
//   import {fetchList as fetchBrandList} from '@/api/brand'
//   import {fetchListWithChildren} from '@/api/productCate'

  const defaultListQuery = {
    keyword: null,
    pageNum: 1,
    pageSize: 5,
    publishStatus: null,
    verifyStatus: null,
    productSn: null,
    productCategoryId: null,
    brandId: null
  };
  export default {
    name: "FreightList",
    data() {
      //首重验证规则
      const freeAmount= (rule, value, callback) => {
        if(value === null || value === '') {
          callback(new Error('首重不能为空'))
        }else {
          // if(/^\d+$/.test(value) == false) {
          //   callback(new Error('首重只能为正整数'))
          // }else{
            if(value< 1) {
                callback(new Error('不能小于1'))
            }
            // else if(value > 99){ //设置最大值
            //     callback(new Error('首重只能为正整数，且不大于99'))
            // }
            else {
                callback()
            }
      //    }
        }
      };
      //续重验证规则
      const continueWeight= (rule, value, callback) => {
        if(value === null || value === '') {
          callback(new Error('续重不能为空'))
        }else {
          // if(/^\d+$/.test(value) == false) {
          //   callback(new Error('续重只能为正整数'))
          // }else{
            if(value< 1) {
                callback(new Error('不能小于1'))
            }
            // else if(value > 99){ //设置最大值
            //     callback(new Error('首重只能为正整数，且不大于99'))
            // }
            else {
                callback()
            }
        //  }
        }
      };
      //首重收费验证规则
      const postage = (rule, value, callback) => {
       let val = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(value);
        if(!value){
            callback(new Error('请输入首重收费'))
        }else{
            // if(value>9999.99){
            //     callback(new Error('销售价最大为9999.99'))
            // }
            if (!val) {
                callback(new Error('首重收费必须为大于等于0的正数，支持小数点后两位'))
            } else{    
                callback()
            }
        }
      };
      //续重收费验证规则
      const continmeFee = (rule, value, callback) => {
       let val = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(value);
        if(!value){
            callback(new Error('请输入续重收费'))
        }else{
            // if(value>9999.99){
            //     callback(new Error('销售价最大为9999.99'))
            // }
            if (!val) {
                callback(new Error('续重收费必须为大于等于0的正数，支持小数点后两位'))
            } else{    
                callback()
            }
        }
      };
      //仓库验证规则
      const depotId= (rule, value, callback) => {
        if(value === null || value === '') {
          callback(new Error('仓库不能为空'))
        }else {
          if(/^\d+$/.test(value) == false) {
            callback(new Error('仓库id只能为正整数'))
          }else{
            if(value< 1) {
                callback(new Error('不能小于1'))
            }
            else {
                callback()
            }
          }
        }
      };
      return {
          list:[],
          depotList:[],//仓库信息列表
          listQuery:Object.assign({}, defaultListQuery),
          newForm:{//新增运费弹框里内容
            name:'',
            // chargeType:0,//
            // area:"",
            // dest:"",
            // arriveTime:"",
            depotId:null,
            freeAmount:"",
            postage:null,
            depotName:"",
            // continueWeight:"",
            // continmeFee:null,
          },
          editForm: {//编辑运费弹框里内容
            id:0,
            // chargeType:0,//
            // area:"",
            // dest:"",
            // arriveTime:"",
            depotId:null,
            freeAmount:"",
            postage:null,
            depotName:"",
            // continueWeight:"",
            // continmeFee:null,
          },
          newFormRules:{
            name:[
                { required: true,  message: '运费名称不能为空', trigger: ['blur','change']}
             ],
            // area:[
            //   { required: true,  message: '目的地省份不能为空', trigger: ['blur','change']}
            // ],
            // dest:[
            //   { required: true,  message: '目的地市区不能为空', trigger: ['blur','change']}
            // ],
            // arriveTime:[
            //   { required: true,  message: '到达时间不能为空', trigger: ['blur','change']}
            // ],

            freeAmount:[
              { required: true,  message: '首重不能为空', trigger: ['blur','change']},
              {validator: freeAmount}
            ],
            postage:[
              { required: true,  message: '首重费用不能为空', trigger: ['blur','change']},
              {validator: postage}
            ],
            // continueWeight:[
            //   { required: true,  message: '续重不能为空', trigger: ['blur','change']},
            //   {validator: continueWeight}
            // ],
            // continmeFee:[
            //   { required: true,  message: '续重费用不能为空', trigger: ['blur','change']},
            //   {validator: continmeFee}
            // ],
            depotId:[
              { required: true,  message: '仓库不能为空', trigger: ['blur','change']},
              {validator: depotId}
            ],
            
          },
          editFormRules:{
            name:[
                { required: true,  message: '运费名称不能为空', trigger: ['blur','change']}
             ],
            // area:[
            //   { required: true,  message: '目的地省份不能为空', trigger: ['blur','change']}
            // ],
            // dest:[
            //   { required: true,  message: '目的地市区不能为空', trigger: ['blur','change']}
            // ],
            // arriveTime:[
            //   { required: true,  message: '到达时间不能为空', trigger: ['blur','change']}
            // ],
            freeAmount:[
              { required: true,  message: '首重不能为空', trigger: ['blur','change']},
              {validator: freeAmount}
            ],
            postage:[
              { required: true,  message: '首重费用不能为空', trigger: ['blur','change']},
              {validator: postage}
            ],
            // continueWeight:[
            //   { required: true,  message: '续重不能为空', trigger: ['blur','change']},
            //   {validator: continueWeight}
            // ],
            // continmeFee:[
            //   { required: true,  message: '续重费用不能为空', trigger: ['blur','change']},
            //   {validator: continmeFee}
            // ],
            depotId:[
              { required: true,  message: '仓库不能为空', trigger: ['blur','change']},
              {validator: depotId}
            ],
          },
          currentOpeId:0,//编辑角色的当前运费id
          allRoleList:[],//所有的角色列表
          FreightRoleId:[],//当前运费的role id
          selectedRole:[],//运费弹窗里选择的选择的role id
          isNewFreightOpen:false,//新增运费弹窗
          isEditFreightOpen:false,//编辑运费弹窗
          //isRoleOpen:false,//编辑角色弹窗
          listLoading:false,
      }
    },  
    mounted() {
      this.getList();
      this.fetchDepotList();
    },
    methods:{
      depotChange(depotId){
        let id = depotId;
        let depotName="";
        for(const item of this.depotList){
          if(item.id === id){
            depotName = item.name;
            break
          }
        }
        this.depotName = depotName;
        console.log(depotName);
      },
      getList() {
        this.listLoading = true;
        //console.log(this.listQuery);
        fetchList().then(response => {
            this.listLoading = false;
            if(!response.data){
              this.list = []
            }else{
              this.list = response.data;
            //  let data = response.data;
            //   fetchDepotList().then(res=>{
            //     if(res.code ==200){
            //       if(res.data){
            //         let depotData = res.data;
            //         data.forEach((item,index)=>{

            //         })
            //       }
            //     }
            //   })
            }
            
            //this.total = response.data.total;
            //console.log(this.list);
        });
      },
      fetchDepotList(){
        let self = this;
        fetchDepotList().then(res=>{
          if(res.code ==200){
            self.depotList = res.data;
          }
        })
      },
      handleEditFreight(index,item){
        this.isEditFreightOpen = true;
        this.editForm = Object.assign({},item);
      },

      handleAddFreight(){
        this.isNewFreightOpen = true;
      },
      
      saveNewFreight(formName){

        this[formName].depotName = this.depotName;
        // this[formName].freeAmount = this[formName].freeAmount;
        // this[formName].postage = this[formName].postage;
        console.log(this[formName])
        this.$refs[formName].validate((valid) => {
          if (valid) {
            createFreight(this.newForm).then(response=>{
              if(response.code == 200){
                  this.$message({
                    message: '新建成功',
                    type: 'success',
                    duration: 1000
                  });
              this.isNewFreightOpen=false;
              this.$refs[formName].resetFields();
              this[formName].depotId =null;
              this.getList();
              }
            })
          }else{
            this.$message({
              message: '数据有误，请修改',
              type: 'warning',
              duration: 1000
            });
          }
        })
      },
      saveFreightInfo(formName){
          //console.log(this.editForm);
          let passTemp= this.editForm.password;
          if (!passTemp){
            delete this.editForm.password
          }
          this[formName].depotName = this.depotName;
        //    this[formName].freeAmount = this[formName].freeAmount;
        // this[formName].postage = this[formName].postage;
          console.log(this.editForm);
        updateFreight(this.editForm.id,this.editForm).then(response=>{
            this.$message({
                message: '修改成功',
                type: 'success',
                duration: 1000
            });
            this.isEditFreightOpen=false;
            this.getList();
        });
      },
      handleUpdateRole(index,item){
        //console.log(item.id);
        this.currentOpeId = item.id;
        this.getCurFreightRole();
      },
      handleUpdateDepot(){
        let self = this;
        
      },
      // getRoleList() {
      //   let self = this;
      //   fetchRoleList().then(response => {
      //       if(response.code === 200){
      //         self.allRoleList = response.data;
      //       }
      //   });
      // },
      // getCurFreightRole(){
      //   let self = this;
      //   let id = self.currentOpeId;
      //   getCurFreightRole(id).then(res =>{
      //     let roleInfo = res.data;
      //     let roleIds =[];
      //     roleInfo.forEach(item=>{
      //       roleIds.push(item.id);
      //     })
      //     self.FreightRoleId = roleIds; //当前运费的role id
      //     self.selectedRole = JSON.parse(JSON.stringify(roleIds));
      //     self.isRoleOpen =true;
      //   })
      // },
      // roleChange(){
      //   console.log(this.selectedRole)
      // },
      // saveFreightRoleInfo(){
      //   let self = this;
      //   if (!self.selectedRole || self.selectedRole.length ==0){
      //     this.$message({
      //       message: '请选择合适的角色',
      //       type: 'warning',
      //       duration: 1000
      //     });
      //     return;
      //   }
      //   let params = new URLSearchParams();
      //   params.append('adminId', self.currentOpeId);
      //   params.append('roleIds', self.selectedRole);
      //   // updateFreightRoleInfo(params).then(res=>{
      //   //   if(res.code === 200){
      //   //     this.$message({
      //   //       message: '角色修改成功',
      //   //       type: 'success',
      //   //       duration: 1000
      //   //     });
      //   //     self.isRoleOpen = false;
      //   //     self.getList();
      //   //   }
      //   // })
      // },
      handleDeleteFreight(index,item){
          let self = this;
           self.$confirm('删除该运费, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                deleteFreight(item.id).then(response=>{
                    if(response.code === 200){
                        self.$message({
                            message: '删除成功',
                            type: 'success',
                            duration: 1000
                        });
                        self.getList();
                    }
                });
            }).catch(() => {
                // self.$message({
                //     type: 'info',
                //     message: '已取消删除'
                // });          
            });
      },
      
    }
  }
</script>
<style scoped>
.btn-add{
  margin-top: -8px;
}
/* 弹出框的宽度 */
.adjustmentBox >>> .el-dialog{
  width: 28rem;
} 
</style>